﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YJKRevitBase.WinForm;
using YRevitJig;
using YJKRevitDimensionText.Utility;
using YJKRevitView;

namespace YJKRevitDimension.ArrowDimension
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdArrowDimension : YJKCommandManual
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		protected override Result YJKExcute(ExternalCommandData cmdData, ref string message, ElementSet elements)
		{
			CmdViewType types = (CmdViewType)111;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			if (CmdArrowDimension._hWndRevit == null)
			{
				Process[] processesByName = Process.GetProcessesByName("Revit");
				if (processesByName.Length != 0)
				{
                    CmdArrowDimension._hWndRevit = new YJKRevitBase.WinForm.WindowHandle(processesByName[0].MainWindowHandle);
				}
			}
			Autodesk.Revit.DB.View activeView = cmdData.Application.ActiveUIDocument.ActiveView;
			if (!Helper.ViewValidating(cmdData.Application.ActiveUIDocument.Document, activeView, ref message))
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			UIDocument activeUIDocument = cmdData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			Document document2 = activeUIDocument.Document;
			DlgArrowDimensionForm dlgArrowDimensionForm = new DlgArrowDimensionForm(document);
			dlgArrowDimensionForm.Show(CmdArrowDimension._hWndRevit);
			int wMsg = 7;
			CmdArrowDimension.SendMessage(CmdArrowDimension._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			this.PickPoints(activeUIDocument, dlgArrowDimensionForm, ref this.LstPickPoint);
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void PickPoints(UIDocument m_UIdoc, DlgArrowDimensionForm dlgArrowDimension, ref List<XYZ> lstPickPoints)
		{
			ArrowDimData useData = dlgArrowDimension.UseData;
			ViewAssist.ViewValidating(m_UIdoc.Document, m_UIdoc.ActiveView);
			XLineJig xlineJig = new XLineJig(m_UIdoc);
			XYZ xyz = null;
			XYZ xyz2 = null;
			xlineJig.ResetPoint = XUiJigBase.EResetPoint.eByAxis;
			for (;;)
			{
				try
				{
					if (!dlgArrowDimension.IsDisposed)
					{
						if (xyz == null)
						{
							xyz = xlineJig.PickStartPoint("请选择一个点");
							if (xyz == null)
							{
								throw new EscException();
							}
							lstPickPoints.Add(xyz);
						}
						else
						{
							xyz2 = xlineJig.PickEndPoint(xyz, "请选择另一个点");
							if (xyz2 == null)
							{
								throw new EscException();
							}
							lstPickPoints.Add(xyz2);
						}
						if (xyz2 != null && this.CreateLine(m_UIdoc, xyz, xyz2, lstPickPoints))
						{
							xyz = xyz2;
						}
						continue;
					}
					xlineJig.Dispose();
				}
				catch (EscException)
				{
					if (lstPickPoints.Count == 0)
					{
						xlineJig.Dispose();
						dlgArrowDimension.Close();
					}
					else
					{
						if (1 == lstPickPoints.Count)
						{
							xlineJig.Dispose();
							xlineJig = null;
							xlineJig = new XLineJig(m_UIdoc);
							xlineJig.ResetPoint = XUiJigBase.EResetPoint.eByAxis;
							lstPickPoints.Clear();
							xyz = null;
							xyz2 = null;
							continue;
						}
						string empty = string.Empty;
						Document newDoc = null;
						if (useData.BRight)
						{
							if (!string.IsNullOrEmpty(useData.StrArrowAngle) && !string.IsNullOrEmpty(useData.StrDistance) && !string.IsNullOrEmpty(useData.StrTextHeight) && !string.IsNullOrEmpty(useData.StrTextWidth))
							{
								ArrowDimTempFamily.Draw(m_UIdoc, newDoc, useData, lstPickPoints, out empty, true, null);
							}
							else
							{
								YJKMessageBox.Show("请正确输入参数");
							}
						}
						else
						{
							YJKMessageBox.Show("请正确输入参数");
						}
						if (this.LstPreviewCurve.Count > 0)
						{
							this.DeleteLine(m_UIdoc.Document, this.LstPreviewCurve);
						}
						xyz = null;
						lstPickPoints.Clear();
						this.LstPreviewCurve.Clear();
						continue;
					}
				}
				break;
			}
		}

		private bool CreateLine(UIDocument m_UIdoc, XYZ ptStart, XYZ ptEnd, List<XYZ> lstPickPoint)
		{
			Transaction transaction = new Transaction(m_UIdoc.Document);
			try
			{
				transaction.Start("ArrowDimBaseLine");
				Line line = Line.CreateBound(ptStart, ptEnd);
				if (lstPickPoint.Count == 2 && line.Length < 3.0)
				{
					YJKMessageBox.Show("线段过短，请重新点取第二点");
					lstPickPoint.RemoveAt(1);
					transaction.Commit();
					return false;
				}
				this.LstPreviewCurve.Add(m_UIdoc.Document.Create.NewDetailCurve(m_UIdoc.ActiveView, line));
				transaction.Commit();
			}
			catch (Exception)
			{
				transaction.RollBack();
			}
			return true;
		}

		private void DeleteLine(Autodesk.Revit.DB.Document doc, List<DetailCurve> LstPreviewCurve)
		{
			using (Transaction transaction = new Transaction(doc, "Delete Lines"))
			{
				try
				{
					transaction.Start();
					foreach (DetailCurve detailCurve in LstPreviewCurve)
					{
						ElementId id = detailCurve.Id;
						doc.Delete(id);
					}
					transaction.Commit();
				}
				catch (Exception)
				{
					transaction.RollBack();
				}
			}
		}

		public List<XYZ> LstPickPoint = new List<XYZ>();

		public List<DetailCurve> LstPreviewCurve = new List<DetailCurve>();

		public List<string> m_lstOutPutPath = new List<string>();

        public static YJKRevitBase.WinForm.WindowHandle _hWndRevit;
	}
}
